<?php
function cp1251_to_utf8($s) 
  { 
  if ((mb_detect_encoding($s,'UTF-8,CP1251')) == "WINDOWS-1251") 
    { 
    $c209 = chr(209); $c208 = chr(208); $c129 = chr(129); 
    for($i=0; $i<strlen($s); $i++) 
      { 
      $c=ord($s[$i]); 
      if ($c>=192 and $c<=239) $t.=$c208.chr($c-48); 
      elseif ($c>239) $t.=$c209.chr($c-112); 
      elseif ($c==184) $t.=$c209.$c209; 
      elseif ($c==168)    $t.=$c208.$c129; 
      else $t.=$s[$i]; 
      } 
    return $t; 
    } 
  else 
    { 
    return $s; 
    } 
   } 
/**
 * IncomingMail
 *
 * Обработка данных входящей почты
 *
 * @author Дмитрий Кузьма <kouzma.d@gmail.com>
 * @version 1.0
 */
class IncomingMail extends ActiveRecord  {
	protected $tableName = 'incoming_mail';
	public $pkName = 'ID_incoming_mail';
	
  protected $arrWysiwyg = array('sender', 'from');
  
  /**
   * Получает непосредственно мыло по строке мылосодержащей
   * 
   * @param string $strWithEmail
   */
  public function getEMailAdress($strWithEmail) {
  	Service_Debug::setDebug();
  	$posStart = strpos($strWithEmail, '<');
  	if ($posStart === false) return trim($strWithEmail);
  	$posFinish = strpos($strWithEmail, '>', $posStart);
  	return trim(substr($strWithEmail, $posStart + 1, $posFinish - $posStart - 1));
  }
  
  public function getSubject($strSubject) {
  	Service_Debug::setDebug();

  	$posStart = strpos($strSubject, '=?');//=?UTF-8?B?
  	if ($posStart === false) return trim($strSubject);
  	$posCharsetStop = strpos($strSubject, '?', $posStart + 2);
  	$charset = substr($strSubject, $posStart + 2, $posCharsetStop - $posStart - 2);
  	$posCodedStringStart = 1 + strpos($strSubject, '?', $posCharsetStop + 1);
  	
  	$posFinish = strpos($strSubject, '?=', $posStart + 11);
  	return $this->getSubject(
  	  substr($strSubject, 0, $posStart) .
			iconv($charset, 'UTF-8', base64_decode(substr($strSubject, $posCodedStringStart, $posFinish - $posCodedStringStart))) .
			substr($strSubject, $posFinish + 2)
		);  	
  }

}
?>